package zhihui.mobile.manager.token;

import com.google.gson.Gson;
import com.zgm.utils.WaitUtils;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

import zhihui.mobile.bean.token.TokenInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.config.TokenConfig;
import zhihui.mobile.interfaces.net.IHttpCallBackListener;
import zhihui.mobile.manager.AllManagerObvs;
import zhihui.mobile.manager.IManager;
import zhihui.mobile.net.HttpUtils;

/**
 * Created by 张公铭 on 2017/6/28 0028.
 */

public class TokenManager implements IManager
{
    private Logger logger = Logger.getLogger(TokenManager.class);

    private static TokenManager manager;
    private TokenInfo curToken = null;
    public long curSystemTime;
    private Timer timer = new Timer();
    private AtomicBoolean tokenBakc = new AtomicBoolean(false);

    private TokenManager()
    {
        AllManagerObvs.getInstance().addManager(this);
    }

    private static synchronized void createdIns()
    {
        if (manager == null)
        {
            manager = new TokenManager();
        }
    }

    public static TokenManager getInstance()
    {
        if (manager == null)
        {
            createdIns();
        }
        return manager;
    }

    public TokenInfo getCurToken()
    {
        return curToken;
    }

    public void setCurToken(TokenInfo curToken)
    {
        this.curToken = curToken;
    }

    public synchronized boolean getToken()
    {
        if (checkToken())
        {
            return true;
        }

        final AtomicBoolean back = new AtomicBoolean(false);
        Map<String, Object> map = new HashMap<>();
        map.put("clientid", Config.Imei);
        map.put("token", "abcd");
        HttpUtils.post(TokenConfig.token_url, map, new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                try
                {
                    logger.debug("token result:" + result.toString());
                    String state = result.getString("state");
                    if (state.equals(Config.SUCCESS))
                    {
                        Gson gson = new Gson();
                        TokenInfo tokenInfo = gson.fromJson(result.getString("data"), TokenInfo.class);
                        TokenManager.getInstance().setCurToken(tokenInfo);
                        TokenManager.getInstance().curSystemTime = tokenInfo.getTime();
                        TokenManager.getInstance().startTimer();
                        back.set(true);
                    }
                } catch (Exception e)
                {
                    logger.error("解析token失败：" + e.getMessage());
                    back.set(false);
                }
                tokenBakc.set(true);
            }

            @Override
            public void failed(String message)
            {
                back.set(false);
                tokenBakc.set(true);
                logger.error("网络超时,请重新尝试...");

            }
        });
        WaitUtils.Waiting(tokenBakc, 5000);
        return back.get();
    }

    /**
     * 判断token 是否失效
     */
    public synchronized boolean checkToken()
    {
        if (curToken == null || curSystemTime > (curToken.getTime() + 1000 * 60 * 60))
        {
            return false;
        }
        return true;
    }

    public void startTimer()
    {
        if (timer != null)
        {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                curSystemTime += 1000;
            }
        }, 0, 1000);
    }

    @Override
    public void clear()
    {
        AllManagerObvs.getInstance().removeManager(this);
        curToken = null;
        if (timer != null)
        {
            timer.cancel();
            timer = null;
        }
        manager = null;
    }
}
